import 'dart:io';

import 'package:dio/dio.dart';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:flutter_play_android/common/common.dart';

class CookieInterceptor extends Interceptor{
  late final CookieJar cookieJar;

  CookieInterceptor(this.cookieJar);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    cookieJar.loadForRequest(options.uri).then((cookies) {
      cookies.removeWhere((cookie) {
        if (cookie.expires != null) {
          return cookie.expires?.isBefore(DateTime.now()) ?? false;
        }
        return false;
      });
      String cookie = getCookies(cookies);
      if (cookie.isNotEmpty) options.headers[HttpHeaders.cookieHeader] = cookie;
    });
    super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    _saveCookies(response);
    super.onResponse(response, handler);
  }
  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    _saveCookies(err.response);
    super.onError(err, handler);
  }

  _saveCookies(Response? response) {
    if (response != null && response.headers != null) {
      String? uri = response.requestOptions.uri.toString();
      List<String>? cookies = response.headers[HttpHeaders.setCookieHeader];
      if (cookies != null &&
          (uri.contains(Constants.SAVE_USER_LOGIN_KEY) ||
              uri.contains(Constants.SAVE_USER_REGISTER_KEY))) {
        cookieJar.saveFromResponse(
          response.requestOptions.uri,
          cookies.map((str) => Cookie.fromSetCookieValue(str)).toList(),
        );
      }
    }
  }

  static String getCookies(List<Cookie> cookies) {
    return cookies.map((cookie) => "${cookie.name}=${cookie.value}").join('; ');
  }
}